<template>
  <Svga v-if="param.loading" :width="100" :height="100"></Svga>
  
  <div v-else class="app-container">
    <div style="font-weight: 700;padding-bottom: 20px;">订单号：{{ rowData.orderNo }}</div>
    <Progress :userRole="'boxDeal_boxOwnner'" :invoiceStatus="rowData.invoiceStatus" :orderStatus="param.newStep" />
    <el-row style="margin-top: 10px">
        <el-button-group>
          <el-button v-show="param.newStep > 10" icon="edit" @click="param.drawerInvoiceInfo = true">查看发票</el-button>
        </el-button-group>
    </el-row>
    <el-row :gutter="20">
        <el-col :span="18">
            <el-card class="marginTop20">
                <el-row>
                    <el-col :span="14" :align="'left'">
                        <span style="font-size: 16px;font-weight: 600;">{{ rowData.companyName }}</span>
                    </el-col>
                    <el-col :span="10" :align="'right'">
                        <stamp v-if="![20, 25, 30, 35, 40, 45].includes(rowData.processBusinessType)" :rowData="rowData" :rentSource="5" :pageType="'dealBox'" style="margin:10px 50px;position: absolute;right: 0;" />
                        <stampCancel v-else :rowData="rowData" :pageType="'dealBox'" :canceledType="rowData.canceledType" :rentSource="5" :roleType="'boxEast'" style="margin:10px 50px;" />
                    </el-col>
                </el-row>

                <el-row :gutter="40" class="marginTop20">
                    <el-col :span="11"><Carousel v-bind="swiperData" ></Carousel></el-col>
                    <el-col :span="12">
                      <el-row>
                        <el-col :span="24" style="font-size: 18px;font-weight: 700;">{{ rowData.carryCityName }}</el-col>
                        <el-col :span="24">购箱城市:{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</el-col>
                      </el-row>
                      <el-row class="marginTop20">
                        <el-col :span="5" class="marginTop10">售箱单价</el-col> 
                        <el-col :span="18" class="marginTop10" style="color: #ff0000;">
                          <span v-if="!editable"> {{ payCurrency }} {{ rowData.unitPrice }}</span>
                          <span v-else>
                            {{ payCurrency }}
                            <el-input-number v-model="rowData.unitPrice" :controls="false" :min="0" :max="99999"
                              :precision="2" placeholder=" < 100000" size="small" />
                          </span>
                        </el-col>

                        <el-col :span="5" v-if="editable" class="marginTop10">结算币种:</el-col> 
                        <el-col :span="18"  v-if="editable" class="marginTop10">
                          <el-radio-group v-model="rowData.currency">
                            <el-radio value="CNY">人民币（CNY）</el-radio>
                            <el-radio value="USD">美元（USD）</el-radio>
                          </el-radio-group>
                        </el-col>

                        <el-col :span="5" class="marginTop10">箱型</el-col> <el-col :span="18" class="marginTop10">{{ boxInfo.boxTypeInfo1[rowData.boxType] }}</el-col>
                        <el-col :span="5" class="marginTop10">箱况</el-col> <el-col :span="18" class="marginTop10">{{ boxInfo.boxConditionInfo2[rowData.boxCondition] }}</el-col>
                        <el-col :span="5" class="marginTop10">购箱量</el-col> <el-col :span="18" class="marginTop10">{{ rowData.boxQuantity }}个</el-col>
                        <el-col :span="5" class="marginTop10">预计提箱日期</el-col> <el-col :span="18" class="marginTop10" v-if="rowData.planPickupDate">{{ rowData.planPickupDate.substring(0, 10)}}</el-col>

                      </el-row>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
        <el-col :span="6" class="marginTop20">
          <el-card>
            <el-row>
              <el-col :span="12" class="marginTop20">销售金额</el-col><el-col :span="12" style="color: #ff0000;" class="marginTop20">{{ payCurrency }} {{ rowData.amount }}</el-col>
              <el-col :span="12" class="marginTop20">优惠券</el-col><el-col :span="12" class="marginTop20">0.00</el-col>
              <el-col :span="12" class="marginTop20">合计</el-col><el-col :span="12"  style="color: #ff0000;" class="marginTop20">{{ payCurrency }} {{ rowData.amount }}</el-col>
            </el-row>
          </el-card>
        </el-col>
    </el-row>
    <el-card class="pag-container">
      <span class="_before">客户信息</span>
      <el-form inline label-width="60px" style="margin-top: 20px;" label-position="left">
        <el-form-item>
          <div class="div_100">企业名称</div>
          <div>{{ rowData.buyBoxCompanyName }}</div>
        </el-form-item>
        <el-form-item>
          <div class="div_100">联系人</div>
          <div>{{ rowData.contacts }}</div>
        </el-form-item>
        <el-form-item>
          <div class="div_100">联系电话</div>
          <div>+{{rowData.boxEastUserAreaCode}}{{ rowData.tel }}</div>
        </el-form-item>
        <el-form-item>
          <div class="div_100">支付方式</div>
          <div>{{ paymentMethodFilter(rowData.paymentMethod) }}</div>
        </el-form-item>
        <el-form-item>
          <div class="div_100">发票类型</div>
          <div>{{ invoiceTypeFilter(rowData.invoiceType) }}</div>
        </el-form-item>
        <el-form-item>
          <div class="div_100">结算账期</div>
          <template v-if="rowData.status =='2' && rowData.currentNodeType == '10'">
              <el-input v-model="rowData.period" style="width: 50%;">
                <template #suffix>天</template>
              </el-input>
          </template>
          <template v-else>
            <div>{{ rowData.period || "--" }} 天</div>
          </template>
        </el-form-item>
        <el-form-item>
          <div class="div_100">联系客户 </div>
          <div>
            <el-button type="primary" link plain icon="ChatDotSquare"></el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="div_100">留言 </div>
          <div>{{rowData.leaveMsg || "--"}}</div>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="pag-container">
      <span class="_before">售箱人信息</span>
      <el-form inline label-width="60px" style="margin-top: 20px;" label-position="left">
        <el-form-item>
            <div class="div_100">销售人</div>
            <div>{{ user.nickname }}</div>
        </el-form-item>
        <el-form-item>
            <div class="div_100">
              <redStar />操作员
            </div>
          <el-select v-model="param.userSimple" @change="userSimpleChange" :disabled="!editable"
            style="width: 150px;">
            <el-option v-for="item in param.userSimpleList" :key="item.userId" :label="item.nickname"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="pag-container">
      <el-row>
        <el-col :span="8"><span class="_before">出售箱号</span></el-col>
        <el-col :offset="10" :span="6" class="text-right">
          <template v-if="containerInfo.containerData.length && containerInfo.isEditable">
              <el-button type="warning" plain size="small" @click="toEditBoxNumber">{{containerInfo.editButtonName}}</el-button> 
              <el-button type="info" plain size="small" @click="openContainerDialog">添加</el-button>
          </template>
        </el-col>
      </el-row>

     <el-table :data="containerInfo.formatContainer" border height='300' :show-header="false" class="marginTop20">
        <el-table-column type="index" width="50" align="center"/>
        <el-table-column prop="containerNo0" label="Date" >
          <template #default="scope">
            <el-row  v-if="scope.row.containerNo0" justify="center" align="middle">
              <el-col :span="19"><el-input v-model="scope.row.containerNo0" :disabled="containerInfo.editBoxNumber"></el-input></el-col>
              <el-col :offset="1" :span="2" v-if="containerInfo.isEditable"><el-icon @click="delContainer(scope.row.rowIndex,'containerNo0')"><Delete /></el-icon></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="containerNo1" label="Date" >
          <template #default="scope">
            <el-row v-if="scope.row.containerNo1" justify="center" align="middle">
              <el-col :span="19"><el-input  v-model="scope.row.containerNo1" :disabled="containerInfo.editBoxNumber"></el-input></el-col>
              <el-col :offset="1" :span="2" v-if="containerInfo.isEditable"><el-icon  @click="delContainer(scope.row.rowIndex,'containerNo1')"><Delete /></el-icon></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="containerNo2" label="Date"  >
          <template #default="scope">
            <el-row v-if="scope.row.containerNo2" justify="center" align="middle">
              <el-col :span="19"><el-input v-model="scope.row.containerNo2" :disabled="containerInfo.editBoxNumber"></el-input></el-col>
              <el-col :offset="1" :span="2" v-if="containerInfo.isEditable"><el-icon  @click="delContainer(scope.row.rowIndex,'containerNo2')"><Delete /></el-icon></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="containerNo3" label="Date"  >
          <template #default="scope">
            <el-row  v-if="scope.row.containerNo3" justify="center" align="middle">
              <el-col :span="19"><el-input v-model="scope.row.containerNo3" :disabled="containerInfo.editBoxNumber"></el-input></el-col>
              <el-col :offset="1" :span="2" v-if="containerInfo.isEditable"><el-icon  @click="delContainer(scope.row.rowIndex,'containerNo3')"><Delete /></el-icon></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="containerNo4" label="Date"  >
          <template #default="scope">
            <el-row v-if="scope.row.containerNo4" justify="center" align="middle">
              <el-col :span="19"><el-input v-model="scope.row.containerNo4" :disabled="containerInfo.editBoxNumber"></el-input></el-col>
              <el-col :offset="1" :span="2" v-if="containerInfo.isEditable"><el-icon  @click="delContainer(scope.row.rowIndex,'containerNo4')"><Delete /></el-icon></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="containerNo5" label="Date"  >
          <template #default="scope">
            <el-row v-if="scope.row.containerNo5" justify="center" align="middle">
              <el-col :span="19"><el-input v-model="scope.row.containerNo5" :disabled="containerInfo.editBoxNumber"></el-input></el-col>
              <el-col :offset="1" :span="2" v-if="containerInfo.isEditable"><el-icon  @click="delContainer(scope.row.rowIndex,'containerNo5')"><Delete /></el-icon></el-col>
            </el-row>
          </template>
        </el-table-column>
        <template #empty>
          <el-row>
            <el-col :offset="9" :span="2" style="position: relative;"><el-icon size="30px" style="position: absolute;top:15px;"><MessageBox /></el-icon></el-col>
            <el-col :span="12" class="text-left">暂无集装箱箱号数据</el-col>
            <el-col :span="24" v-if="containerInfo.isEditable"><el-button @click="openContainerDialog" size="small">添加箱号</el-button></el-col>
          </el-row>
        </template>
     </el-table>
     <p v-if="containerInfo.tips" style="color: #ff0000;">请点击"编辑完成"，保存编辑后的集装箱号</p>

    </el-card>


    <div class="order-info">

      <!-- 按钮/反馈信息展示 -->
      <el-card class="pag-container">
        <div v-if="rowData.rejectReason && rowData.currentNodeType == 10"
          style="text-align: center;margin-bottom: 20px;">
          <span>
            <span v-if="rowData.frontNodeType == 15">拒绝原因：</span>
            <span v-if="rowData.frontNodeType == 25">驳回原因：</span>
          </span>
          <span>{{ rowData.rejectReason }} </span>
        </div>
        <div v-if="rowData.status == 40 && rowData.canceledType == 10" style="text-align: center;margin-bottom: 20px;">
          <span> 取消原因： </span>
          <span>{{ rowData.remark }} </span>
        </div>
        <div v-if="rowData.currentNodeType == 20" >
          <span class="_before">审核信息</span>
          <h4><redStar />驳回原因</h4>
          <el-input type="textarea" :rows="4" v-model="rowData.reviewRemark" placeholder="请输入驳回原因" />
        </div>
        <div style="width:100%;text-align: center;margin-top: 10px;">
          <span v-if="rowData.status < 3">
            <el-checkbox v-model="checkval" />我已阅读<span @click="showRules(1)">《集装箱租赁业务规则》</span>、<span @click="showRules(2)">《用户服务协议和管理规则》</span>并同意全部条款
          </span>&nbsp;
          <div style="margin-top: 10px;">
            <template v-if="rowData.status == 40 && rowData.canceledType == 10">
              <el-button @click="handleShowWarning('rejectCancel')" type="danger" round> 拒 绝 </el-button>
              <el-button v-if="rowData.currentNodeType == 10" @click="handleMakeSure" type="primary" round> 同 意
              </el-button>
            </template>
            <template v-if="rowData.status < 35">
              <el-button v-if="(param.newStep == 5 || param.newStep == 30) && !rowData.packingNo" @click="handlePacking"
                type="primary">开提箱单</el-button>
              <el-button v-if="param.newStep <= 15 && rowData.status != 3" type="info" @click="handleShowWarning('cancelOrder')">取消订单</el-button>
              <el-button v-if="rowData.currentNodeType == 10 && param.newStep < 5" @click="handleMakeSure" type="success">确认</el-button>
            </template>
            <template v-if="rowData.currentNodeType == 20">
              <el-button @click="handleReject('rejectOrder')" type="danger">驳回</el-button>
              <el-button @click="handleMakeSure" type="primary">通过</el-button>
            </template>
            <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="showContract" type="primary">签署</el-button>
            <el-button v-if="rowData.invoiceStatus == 10 && param.newStep == 10" @click="showInvoice" type="success">开发票</el-button>
          </div>
        </div>
        <el-row style="padding: 20px; text-align: center;">
        <div style="width:100%">
          <div v-if="rowData.status == '20'" style="margin-top: 30px;">
            <el-button type="primary" @click="openTixiang">开提箱单</el-button>
          </div>
        </div>
      </el-row>
      </el-card>

      
      <div v-if="param.newStep == 5" style="padding: 20px;width: 100%;text-align: center "> </div>
    </div>

    <!--添加箱号 -->
    <el-dialog v-model="containerInfo.containerDialog" title="添加箱号" width="30%">
      <el-input v-model="containerInfo.containerStr" :rows="5" type="textarea" placeholder="请输入箱号"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmBoxNumber">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开发票 -->
    <el-drawer v-model="param.drawer" :with-header="false" size="40%">
      <span v-if="param.newStep == 10" class="_before">开发票</span>
      <span v-else class="_before">发票详情</span>
      <el-row class="invoce-box marginTop20 marginBottom20">
        <el-col :span="6" class="text-right">企业名称</el-col><el-col :offset="8" :span="8" style="text-left">{{ rowData.invoiceTitle }}</el-col>
        <el-col :span="6" class="text-right marginTop10">统一社会信用代码</el-col><el-col :offset="8" :span="8" class="marginTop10">{{ rowData.creditCode }}</el-col>
        <el-col :span="6" class="text-right marginTop10">申请发票类型</el-col><el-col :offset="8" :span="8" style="text-left">{{ invoiceTypeFilter(rowData.invoiceType) }}</el-col>
        <el-col :span="6" class="text-right marginTop10">发票类型</el-col><el-col :offset="8" :span="8" style="text-left">
          <el-select v-model="invoiceForm.invoiceType">
            <el-option v-for="(item,index) in param.invoiceTypeList" :key="index" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" class="text-right marginTop10">发票</el-col><el-col :offset="8" :span="8" class="marginTop10">
          <imgUpload ref="invoiceRef" :needOcr="true" :drag="false" @ocrInvoiceNo="ocrInvoiceNo"></imgUpload>
        </el-col>
        <el-col :span="6" class="text-right">发票号</el-col><el-col :offset="8" :span="8" class="text-left">{{invoiceForm.invoiceNo}}</el-col>
      </el-row>
      <span class="_before">收取购箱款</span>
      <el-table :data="rowData.containerNoDetail" border class="marginTop10 marginBottom10">
        <el-table-column prop="orderNo" label="订单号"  width="200"/>
        <el-table-column prop="carryCityName" label="购箱城市">
          <template #default="scope">
            {{scope.row.carryCityName}} /{{scope.row.carryCountryName}}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单日期" >
          <template #default="scope">
            {{formatDate(scope.row.createTime,4) }}
          </template>
        </el-table-column>
        <el-table-column prop="boxQuantity" label="箱量" />
        <el-table-column prop="amount" label="订单金额"  />
        <el-table-column prop="actualPayAmount" label="应收购箱款">
          <template #default="scope">
            {{ param.currency}}{{ scope.row.actualPayAmount}}
          </template>
        </el-table-column>
      </el-table>
      <el-row class="marginTop20 invoce-box" align="middle">
        <el-col :span="24"><span class="_before">合计</span></el-col>
        <el-col :offset="4" :span="6" class="text-right marginTop10">应收箱量总计:</el-col> <el-col :offset="2" :span="12" class="marginTop10">{{totalAccounts.payContainerNum}}个</el-col>
        <el-col :offset="4" :span="6" class="text-right marginTop10">应收购箱款总计:</el-col> <el-col :offset="2" :span="12" class="marginTop10">{{ param.currency}}{{totalAccounts.dealAmount}}</el-col>
        <el-col :offset="4" :span="6" class="text-right marginTop10">实收购箱款总计:</el-col> <el-col :offset="2" :span="12" class="marginTop10">{{ param.currency}}{{totalAccounts.deductAmount}}</el-col>
        <el-col :offset="4" :span="6" class="text-right marginTop10">结算币种:</el-col><el-col :offset="2" :span="12" class="marginTop10">
          <el-radio-group v-model="invoiceForm.payCurrency" @change="changeRadio">
            <el-radio value="CNY" size="large">人民币（￥）</el-radio>
            <el-radio value="USD" size="large">美元（$）</el-radio>
          </el-radio-group>
        </el-col>
        <el-col v-if="param.rateShow" :offset="4" :span="6" class="text-right">本次执行汇率:</el-col>
        <el-col v-if="param.rateShow" :offset="2" :span="12">
          <el-row align="middle">
            <el-col :span="7">1美元=人民币</el-col>
            <el-col :span="6">
              <el-input-number style="width:100%;" v-model.trim="invoiceForm.rate" :controls="false" :precision="2" :min="0.01" :max="99.99" />
            </el-col>
            <el-col :span="4">元</el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
          <el-col :span="24" class="text-center marginTop20"><el-button @click="handleAddInvoice" type="primary" >提交</el-button></el-col>
      </el-row>
    </el-drawer>

    <!-- 发票信息 -->
    <el-drawer v-model="param.drawerInvoiceInfo" :with-header="false">
      <invoiceInfo :rowData="rowData" :param="param"></invoiceInfo>
    </el-drawer>

    <!-- 提箱单信息 -->
    <el-drawer v-model="param.drawer1" title="I am the title" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>提箱单信息
      </span>
      <table style="margin: 30px 0 30px 0;">
        <tbody>
        <tr>租箱企业：{{ packing.agentName }}</tr>
        <tr>提箱单号：{{ packing.packingNo }}</tr>
        <tr>提箱单有效期范围：
          {{ formatDate(packing.packingValidityPeriodStart, 2) }}
          ~
          {{ formatDate(packing.packingValidityPeriodEnd, 2) }}</tr>
        <tr>箱型/箱量/箱况</tr>
        </tbody>
      </table>
      <el-table :data="param.rentBoxTable">
        <el-table-column prop="boxType" align='center' label="箱型"> </el-table-column>
        <el-table-column prop="totalQuantity" align='center' label="箱量"> </el-table-column>
        <el-table-column prop="boxCondition" align='center' label="箱况"> </el-table-column>
      </el-table>
      <div style="box-sizing: border-box; padding: 20px 0 15px 0;">箱号</div>
      <el-table :data="param.containerNoArry">
        <el-table-column prop="containerNo" align='center' label="箱号"></el-table-column>
      </el-table>

      <yardInfoCard :yard="packing"></yardInfoCard>
      <el-row>
        <el-button type="primary" style="margin-top: 50px;text-align: right;">提箱记录</el-button>
      </el-row>
    </el-drawer>
    <!-- 开提箱单 -->
    <el-drawer v-model="param.drawerPacking" :show-close="false">
      <buildPacking :packingInfo="param.packingInfo" @successPacking="successPacking"></buildPacking>
    </el-drawer>
    <!-- dialog -->
    <!-- 确认退款 -->
    <el-dialog v-model="param.dialogRefund" :with-header="false">
      <refundCard :rowData="rowData" :opr="'refund'"></refundCard>
    </el-dialog>
    <!-- E签宝 -->
    <el-dialog v-model="param.dialogEVisibleWarning" @close="handleCloseEQianBao" title="签署" style="width: auto;">
      <iframe v-if="param.dialogEVisibleWarning" :src="param.longContractUrl" width="100%" height="800px"
        frameborder="0"></iframe>
    </el-dialog>
    <!-- 开提箱单 -->
    <el-dialog v-model="param.isPackingList">
      <packingList :rowData="rowData"></packingList>
    </el-dialog>

    <!-- warnning -->
    <el-dialog v-model="param.dialogVisibleRemark" style="width:500px;box-sizing:bolder;padding:40px ">
      <b>确定要取消{{ rowData.orderNo }}订单吗？</b>
      <div style="margin-top: 10px;text-align: left;">
        <b>备注</b>
        <el-input v-model="param.remark" type="textarea"></el-input>
      </div>
      <div style="margin-top: 10px;text-align: left;">
        <el-button @click="handleCancel" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 规则弹窗 -->
    <el-dialog v-model="rulesInfo.dialogRules">
        <BusinessRules1 v-if="rulesInfo.rules1"></BusinessRules1>
        <BusinessRules2 v-if="rulesInfo.rules2"></BusinessRules2>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="rulesInfo.dialogRules = false">关闭</el-button>
          </div>
        </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import Svga from '@/views/components/Svga'
import  Carousel from '@/components/carousel'
import invoiceInfo from '@/views/components/order/invoiceInfo.vue'
import imgUpload from '@/components/upload/index.vue'
import redStar from '@/views/components/redStar.vue';
import Progress from '@/components/progress/index.vue'
import { formatDate } from '@/utils'
import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';
import orderInfo from '@/store/modules/order'
import { downloadPacking, finishPacking, addPacking, getPackingData, getBoxEastTable, getTable } from '@/api/orderManage/packing'
import { getReturnData, addReturn, cancelReturn, downloadReturn } from '@/api/orderManage/returnBox'
import { getOrderInfo, cancelPurchaseBoxOrderById, notarizePurchaseBoxOrder } from '@/api/boxDeal/boxBuy'
import { payBoxLabelInvoice, addRentRequestInvoice, getInvoicesInfo, purchaseBoxUploadingInvoice } from '@/api/invoice'
import yardInfoCard from '@/views/components/boxYard/yardInfo.vue'
import refundCard from '@/views/components/order/refundCard'
import EQianBao from '@/views/components/EQianBao'
import packingList from '@/views/components/packingList.vue';
import { numMulti } from '@/utils/compute'
import { ElLoading, ElMessage } from 'element-plus';
import buildPacking from '@/views/components/packingBuild.vue';
import stamp from '@/views/components/stamp';
import stampCancel from '@/views/components/stamp/stampCancel';
import  BusinessRules1 from '@/components/protocolRegulations/businessRules1'
import  BusinessRules2 from '@/components/protocolRegulations/businessRules2'
import boxInfo from '@/constant/containerInfo';


onActivated(() => {
  containerInfo.formatContainer = []
  containerInfo.containerData = []
  containerInfo.containerStr = ''
  const rowData = orderInfo().rowData
  param.containerNos = ""
  checkval.value = false
  containerInfo.isEditable = false
  getSetOrderInfo(rowData)
  containerInfo.editBoxNumber = true
})

const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
    height:"450px"
  }
})
//集装箱号数组集合
const containerInfo = reactive({
  containerDialog:false,
  editBoxNumber:true,
  containerData:[], // 集装箱箱号集合 array
  containerNo:'',  //  全部集装箱箱号 字符串
  containerStr:'', // 添加集装箱箱号弹窗 字符串
  formatContainer:[],  //用于集装箱数据展示 json
  editButtonName:"编辑",
  tips:false,
  isEditable:false  //集装箱是否可编辑 true：可编辑  false：不可编辑
}) 

const formatConversion = (val:array) => {  // 添加的箱号转为二维数组
  const chunkSize = 6;
  const result = [];
  let rowIndex = 0
  
  for (let i = 0; i < val.length; i += chunkSize) {
    const chunk = val.slice(i, i + chunkSize);
    const row = {};
    chunk.forEach((value, index) => {
      row[`containerNo${index}`] = value;
    });
    
    row['rowIndex'] = rowIndex
    rowIndex = rowIndex + 1
    result.push(row);
  }

  containerInfo.formatContainer = result
}

const toEditBoxNumber = () =>{
  if(!containerInfo.containerData.length) return ElMessage.warning("未有可编辑集装箱，请先添加集装箱")
  containerInfo.editBoxNumber = !containerInfo.editBoxNumber
  if(containerInfo.editBoxNumber){
    containerInfo.editButtonName = "编辑"
    containerInfo.tips = false
  }else{
    containerInfo.editButtonName = "编辑完成"
    containerInfo.tips = true
  }

  jsonConvertArr(containerInfo.formatContainer) // 删除一个数据后 更新table数据 把json格式数据 转换为一维数组格式
  formatConversion(containerInfo.containerData)  // 重新渲染箱号展示 把一维数组数据转换为 json数据格式 用于展示
  arrayConverStr(containerInfo.containerData)  // 更新 containerInfo.containerNo 用于数据提交
}

// 将编辑后的json数据转成长数组格式 [1,2,3,4,5,6,7,8,9]
const jsonConvertArr = (jsonVal:array) => {
  let newArray = []
  jsonVal.forEach((item)=>{
    for (const key in item) {
      if (item.hasOwnProperty(key) && item[key] && key != 'rowIndex' ) { 
        newArray.push(item[key])
      }
    }
  })
  containerInfo.containerData = newArray
}
// 将长数组（一维数组）转换为字符串
const arrayConverStr = (val:array)=> {
  if(val.length > 0){
    containerInfo.containerNo = val.join(",")
  }
  
}

// 删除集装箱
const delContainer = (index:number,col:string)=>{
  if(col){
    delete containerInfo.formatContainer[index][col]
    jsonConvertArr(containerInfo.formatContainer) // 删除一个数据后 更新table数据 把json格式数据 转换为一维数组格式
    formatConversion(containerInfo.containerData)  // 重新渲染箱号展示 把一维数组数据转换为 json数据格式 用于展示
    arrayConverStr(containerInfo.containerData)  // 更新 containerInfo.containerNo 用于数据提交
  }else{
    ElMessage.warning('删除数据失败，请刷新页面！')
  }
}

// 打开添加集装箱号按钮
const openContainerDialog = () =>{
  containerInfo.containerStr = ""
  containerInfo.containerDialog=true
}
//添加箱号确认按钮
const confirmBoxNumber = () => {
  if(containerInfo.containerStr){
    let dataArr = containerInfo.containerStr.replace(/，/g, ",").split(",")
    if(Array.isArray(dataArr)){
      dataArr.forEach(item =>{
        containerInfo.containerData.push(item.toUpperCase())
      })
    }
    const checkboxQuantity = rowData.value.boxQuantity || 0 // 添加集装数量 不能超过购箱量
    containerInfo.containerData = [...new Set(containerInfo.containerData.slice(0, checkboxQuantity))]
    formatConversion(containerInfo.containerData) // 更新  containerInfo.formatContainer 用于展示
    arrayConverStr(containerInfo.containerData)  // 更新 containerInfo.containerNo 用于数据提交
    containerInfo.containerDialog = false
  }else{
    ElMessage.warning("请输入箱号")
  }
  
}

const param = reactive({
  loading: false,
  num: 1,
  activeNames: '',
  drawer: false,
  drawer1: false,
  drawer2: false,
  newStep: 1,
  dialogVisible: false,
  invoiceTypeList: [    // 5-增值税普通发票  10-增值税专用发票 15-形式发票
    { value: 5, label: '增值税普通发票' }, 
    { value: 10, label: '增值税专用发票' },
    { value: 15, label: '形式发票' }
  ],
  //订单分配  
  paymentMethodList: [{ value: 5, label: '对公转账' }, { value: 10, label: '在线支付' }],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  // allocation: [{ 'operateUsers': [3, 5], "businessUser": 4, "businessNo": "NO1234567890" }],
  containerNoArry: [],
  currency:"",
  rateShow:false
})
const payCurrency = computed(() => {
  return rowData.value.currency == 'CNY' ? '￥' : '$'
})
let editable = computed(() => { // 是否可编辑
  const couldEdit = !(rowData.value.status >= 5 || rowData.value.currentNodeType != 10)

  return couldEdit
})

//获取数据
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const user = userStore.getUser() //user信息
const rowData = ref({})
const getSetOrderInfo = async (row: any) => {
  if(!row.id) return 
  await getOrderInfo(row.id).then((res: any) => {
    const result = res.data
    param.newStep = result.status
    rowData.value = result
    rowData.value.mainFileList = JSON.parse(result.mainFileList)
    swiperData.list = result.mainFileList
    console.log("esult.statusesult.status",result.status,result.currentNodeType)
    if(result.status == "2" && result.currentNodeType == "10" ){
      containerInfo.isEditable = true
    }
    if (!result.containerNo) return 
    let containerNoStr = result.containerNo.split(',').join(',')
    param.containerNos = containerNoStr.replace('[', '').replace(']', '') || null
    containerInfo.containerStr = result.containerNo
    containerInfo.containerData = result.containerNo.split(',')
    formatConversion(containerInfo.containerData) // 更新  containerInfo.formatContainer 用于展示
    arrayConverStr(containerInfo.containerData)  // 更新 containerInfo.containerNo 用于数据提交
    
    param.rate = result.rate || null
  })
  await getUserSimpleList()
  userSimpleChange(rowData.value.boxEastOperatorUserId)
}



watch(() => rowData.value.payCurrency, (newVal, oldVal) => {
  param.payCurrency = newVal
})

// 发票识别
const ocrInvoiceNo = (val: any) => {
  invoiceForm.invoiceNo = val.data.invoiceNo
}

// 是否显示汇率
const showRateOrderInfo = computed(() => {
  return rowData.value.payCurrency != rowData.value.targetCurrency
})
const showRateInvoiceForm = computed(() => {
  return invoiceForm.payCurrency != rowData.value.targetCurrency
})

const totalAccounts = ref({})
// 发票信息
const showInvoice = async () => {
  if(rowData.value.status < 3){
    if(!checkval.value) return ElMessage.warning('请先阅读并同意《集装箱租赁业务规则》、《用户服务协议和管理规则》') 
  }
  
  getInvoicesInfo(rowData.value.invoiceId).then((res: any) => {
    let data = res.data
    rowData.value.invoiceTitle = data.invoiceTitle
    rowData.value.creditCode = data.creditCode
    rowData.value.invoiceType = data.invoiceType
    rowData.value.invoiceStatus = data.invoiceStatus
    param.currency = data.currency == "USD" ? "$" : "￥"
    invoiceForm.payCurrency = data.currency
    invoiceForm.rate = data.rate
    invoiceForm.invoiceNo = data.invoiceNo
    rowData.value.containerNoDetail = JSON.parse(data.containerNoDetail) //订单内开提箱单 只有一条信息
    totalAccounts.value.payContainerNum = data.payContainerNum
    totalAccounts.value.dealAmount = data.dealAmount
    totalAccounts.value.deductAmount = data.deductAmount
  })
  param.drawer = true
}

// 确定订单
const handleSign = () => {
  if (showRateOrderInfo.value && !param.rate) {
    ElMessage.warning('请输入汇率')
    return
  }
}

// 开提箱单
const openTixiang = () => {
  if (rowData.value.status < 3) {
    if(!checkval.value) return ElMessage.warning('请先阅读并同意《集装箱租赁业务规则》、《用户服务协议和管理规则》') 
  }
 
  param.isPackingList = true
}

const activeSign = () => {
  if (param.containerNos) {
    param.containerNos = param.containerNos.replace('，', ',')
  }
  const data = {
    "id": rowData.value.id,
    "unitPrice": rowData.value.unitPrice,
    "targetCurrency": rowData.value.payCurrency,
    "containerNo": param.containerNos || '',
    "rate": param.rate - 0
  }
  notarizePurchaseBoxOrder(data).then(res => {
    getSetOrderInfo(rowData.value)
    param.dialogVisibleEQianBao = false
  })
}

//取消订单
const handleCancel = () => {
  if (!param.remark) {
    return ElMessage.warning('请输入取消原因')
  }
  const data = {
    id: rowData.value.id,
    remark: param.remark
  }
  cancelPurchaseBoxOrderById(data).then(res => { })
  param.dialogVisibleRemark = false
}

//修改订单
import { updatePurchaseBoxOrder } from '@/api/boxDeal/boxBuy'
const handleUpdateOrder = async () => {
  let result = false
  const boxEastOperator = param.userSimpleData
  if (!(boxEastOperator && boxEastOperator.userId)) {
    ElMessage({ message: '请选择操作员', type: 'warning' })
    return false
  }
  if (rowData.value.status != 2) { // 确认阶段可以修改订单 
    return true
  }
  const data = {
    "id": rowData.value.id,
    "unitPrice": rowData.value.unitPrice,
    "targetCurrency": rowData.value.payCurrency,
    "currency":rowData.value.currency,
    "boxEastOperatorUserId": boxEastOperator.userId,
    "boxEastOperatorUserName": boxEastOperator.nickname,
    "boxEastOperatorUserAreaCode": boxEastOperator.areaCode,
    "boxEastOperatorUserTel": boxEastOperator.mobile,
    "containerNo":containerInfo.containerNo,
    "period":rowData.value.period
  }

  await updatePurchaseBoxOrder(data).then((res: any) => {
    result = true
  }).catch((err: any) => {
    result = false
  })
  return result
}

//待确认->通过、确认 btn
import { processApproved, processRejected } from '@/api/orderCheck/index'
const handleMakeSure = async () => {
  if(rowData.value.status < 3){
    if(!checkval.value) return ElMessage.warning('请先阅读并同意《集装箱租赁业务规则》、《用户服务协议和管理规则》') 
  }
  
  if (!rowData.value.unitPrice) return ElMessage({ message: '租赁单价 不能为空', type: 'warning' })
  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId }
  param.loading = true
  const result = await handleUpdateOrder()
  if (!result) return param.loading = false
  processApproved(data).then(async () => {
    ElMessage({ message: '确认成功', type: 'success' })
    await getSetOrderInfo(rowData.value)
    containerInfo.isEditable = false
    param.loading = false
  }).catch((err: any) => {
    param.loading = false
  })

}
//待确认->驳回 btn 
const handleReject = () => {
  if (!rowData.value || !rowData.value.reviewRemark) {
    return ElMessage({ message: '请输入驳回 原因', type: 'warning' })
  }
  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId, "reviewRemark": rowData.value.reviewRemark }
  processRejected(data).then(() => {
    ElMessage({ message: '驳回成功', type: 'success' })
    getSetOrderInfo(rowData.value)
  }).catch((err: any) => {
  })
}

//开发票
const invoiceRef = ref()
const invoiceForm = reactive({
  invoiceNo: '',
  invoiceUrl: '',
  rate: 1,
  payCurrency: ''
})
const handleAddInvoice = () => {
  if (showRateInvoiceForm.value && !invoiceForm.rate) {
    return ElMessage.warning('请输入汇率')
  }
  const invoiceUrl = invoiceRef.value.resultList || []
  // const rate = showRateInvoiceForm.value ? invoiceForm.rate : 0
  const data = {
    "id": rowData.value.invoiceId,
    "invoiceNo": invoiceForm.invoiceNo,
    "invoiceUrl": JSON.stringify(invoiceUrl),
    "invoiceType": invoiceForm.invoiceType,
    "rate": invoiceForm.rate || null,
    "payCurrency": invoiceForm.payCurrency
  }
  purchaseBoxUploadingInvoice(data).then((res: any) => {
    getSetOrderInfo(rowData.value)
    param.drawer = false
  })
}

// 调取 eQuanBao 长链接
import { getContractList, getEqbContractOrderInfo } from '@/api/contract/eQianBao'
const showContract = async (val: any) => {
  if(rowData.value.status < 3){
    if(!checkval.value) return ElMessage.warning('请先阅读并同意《集装箱租赁业务规则》、《用户服务协议和管理规则》') 
  }
  
  param.loading = true
  getEqbContractOrderInfo({ "orderId": rowData.value.id, companyId: rowData.value.companyId, businessType: '15' }).then((res: any) => {
    param.longContractUrl = res.data.longContractUrl
    if (param.longContractUrl) {
      param.dialogEVisibleWarning = true
    } else {
      return ElMessage.warning('系统繁忙！请稍后再试')
    }
    param.loading = false
  }).catch(() => {
    ElMessage.warning('系统繁忙！请稍后再试')
    param.loading = false
  })
}

//E签宝关闭
const handleCloseEQianBao = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '数据更新中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  await setTimeout(async () => {
    getSetOrderInfo(rowData.value)
    loading.close()
  }, 10000)
}

//开提箱单
const handlePacking = () => {
  const row = rowData.value
  param.packingInfo = {
    orderType: 15, //箱贸易
    boxType: row.boxType,
    boxCondition: row.boxCondition,
    orderNo: row.orderNo,
    planPickupDate: row.planPickupDate,
    createTime: row.createTime,
    id: row.id, // 订单id
    priceList: [{ boxType: row.boxType, boxCondition: row.boxCondition, number: row.boxQuantity, }],
    // priceList:[{boxType:'',boxCondition:'',number:'',}]
  }
  param.drawerPacking = true
};
const successPacking = () => {
  ElMessage.success('提箱单开具成功！')
  getSetOrderInfo(rowData.value)
  param.drawerPacking = false
}

//过滤
const invoiceTypeFilter = (val: any) => {
  if (val) {
    const filterCode = { 5: '增值税普通发票', 10: '增值税专用发票', 15: '形式发票' } // 5 - 增值税普通发票  10 - 增值税专用发票 15 - 形式发票
    return filterCode[val]
  }
}
const paymentMethodFilter = (val: any) => {
  if (val) {
    const filterCode = { 5: '对公转账', 10: '在线支付' } //5-对公转账  10-在线支付。
    return filterCode[val]
  }
}
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

const packing = ref({})
//下载
//packing
const downloadPackings = () => {
  downloadPacking(rowData.value.packingId).then((res: any) => {
  })
}

// 获取操作员列表
import { userSimpleList } from '@/api/user/index'
import { fa } from 'element-plus/es/locale/index.mjs';
const getUserSimpleList = async (data = {}) => {
  await userSimpleList(data).then(res => {
    param.userSimpleList = res.data || []
  })
}

// 操作员列表change
const userSimpleChange = (val: any) => {
  if (!val) return
  param.userSimpleData = param.userSimpleList.find((item: any) => item.userId == val)
  param.userSimple = val
}


const rulesInfo = reactive({
  dialogRules:false,
  rules1:false,
  rules2:false
})

const checkval = ref(false)
const showRules = (val:number) => {  // 显示阅读业务规则
  rulesInfo.dialogRules = true
  rulesInfo.rules1 = false
  rulesInfo.rules2 = false
  switch (val) {
    case 1:
      rulesInfo.rules1 = true
      break;
    case 2:
      rulesInfo.rules2 = true
      break;
  }

}

const changeRadio = (val:string) => {
   val = val == "USD" ? "$" : "￥"
  if(val == param.currency){
      param.rateShow = false
      invoiceForm.rate = 1
  }else{
    param.rateShow = true
  }
}
</script>

<style lang="scss" scoped>
.div_100 {
  min-width: 80px;
  width: 100%;
  font-weight: 600;
  display: block;
}


.order-info {
  margin-top: 10px;
}

.pag-container {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}

.table_box {
  font-size: 14px;
  width: 400px;
  margin-top: 10px;
  margin-bottom: 30px;
  text-align: left;
  border-collapse: separate;
  border-spacing: 0px 10px;

  tr>td~td {
    font-weight: bold;
  }
}

.ruler-box .el-col{
    margin: 5px 0;
    color: #333;
  }
  .invoce-box{
    border-top: 1px solid #ddd;
    border-bottom: 1px solid #ddd;
    padding: 20px 0;
  }
</style>